﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Pvf.Core
{
    public class PvfFileContainer : IFileContainer
    {
        /// <summary>
        /// 
        /// </summary>
        public IList<IFile> Items => _files;

        /// <summary>
        /// 
        /// </summary>
        public IPvfEnv Env { get; }

        /// <summary>
        /// 
        /// </summary>
        public IFileContainer Parent { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 
        /// </summary>
        private readonly List<IFile> _files = new List<IFile>();

        public PvfFileContainer(IPvfEnv env)
        {
            Env = env;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="file"></param>
        /// <returns></returns>
        public T Add<T>(T file) where T : IFile
        {
            if (file.Parent != null)
            {
                throw new NotSupportedException("当前文件已有父节点");
            }

            file.Parent = this;

            _files.Add(file);

            return file;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="name"></param>
        /// <returns></returns>
        public T Get<T>(string name) where T : IFile
        {
            return (T)_files.Find(x => 0 == string.Compare(x.Name, name, StringComparison.CurrentCultureIgnoreCase));
        }

        public override string ToString()
        {
            return $"[{Items.Count}]{Name}";
        }

        public void Sort(bool desc = false)
        {
            _files.Sort((x, y) =>
            {
                var r = string.Compare(x.Name, y.Name, StringComparison.CurrentCultureIgnoreCase);
                return desc ? (r == 1 ? -1 : r == -1 ? 1 : r) : r;
            });
        }

        public string[] GetTopFileContainersName()
        {
            return Items.Where(x => x is PvfFileContainer).Select(x => x.Name).ToArray();
        }

        public IFileContainer[] GetTopFileContainers()
        {
            return Items.Where(x => x is PvfFileContainer).Cast<IFileContainer>().ToArray();

        }

        public string[] GetTopFilesName()
        {
            return Items.Where(x => !(x is PvfFileContainer)).Select(x => x.Name).ToArray();
        }

        public IFile[] GetTopFiles()
        {
            return Items.Where(x => !(x is PvfFileContainer)).ToArray();
        }
    }
}
